<template>
  <div class="app-container app-js df fdc guide-container">
    <el-form class="top-form guide-search" :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="8" :lg="6">
          <el-form-item label="一级网格" prop="primaryGrid">
            <el-select v-model="queryParams.primaryGrid" placeholder="请选择一级网格" clearable style="width: 200px">
              <el-option v-for="item in primaryGrid" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6">
          <el-form-item label="二级网格" prop="secondaryGrid">
            <el-input
              v-model="queryParams.secondaryGrid"
              placeholder="请输入二级网格"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6">
          <el-form-item label="网格属性" prop="gridAttributes">
            <el-select v-model="queryParams.gridAttributes" placeholder="请选择网格属性" clearable style="width: 200px">
              <el-option v-for="item in gridAttr" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6">
          <el-form-item label="存量提示" prop="stockPrompt">
            <el-select v-model="queryParams.stockPrompt" placeholder="请选择存量提示" clearable style="width: 200px">
              <el-option v-for="item in stockPrompt" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6">
          <el-form-item label="所属地区" prop="areaId">
            <tree-select
              v-model="queryParams.areaId"
              :options="data.areaOptions"
              :obj-map="{
                value: 'areaId',
                label: 'areaName',
                children: 'children'
              }"
              placeholder="请选择所属地区"
              style="width: 200px"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6">
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:guide:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate" v-hasPermi="['system:guide:edit']">
          修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:guide:remove']">
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Upload" @click="handleImport" v-hasPermi="['system:guide:import']">导入</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <div class="f1 guide-table">
      <el-table height="100%" v-loading="loading" :data="guideList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" type="index" width="60" />
        <el-table-column label="一级网格" align="center" prop="primaryGrid" :show-overflow-tooltip="true" />
        <el-table-column label="二级网格" align="center" prop="secondaryGrid" :show-overflow-tooltip="true" width="200" />
        <el-table-column label="网格属性" align="center" prop="gridAttributes" :show-overflow-tooltip="true" />
        <el-table-column label="现持证户数" align="center" prop="licensedHouseholds" :show-overflow-tooltip="true" />
        <el-table-column label="户数" align="center" prop="numberHouseholds" :show-overflow-tooltip="true" />
        <el-table-column label="预设户数" align="center" prop="preNumber" :show-overflow-tooltip="true" />
        <el-table-column label="差值" align="center" prop="difference" :show-overflow-tooltip="true" />
        <el-table-column label="存量提示" align="center" prop="stockPrompt" :show-overflow-tooltip="true" />
        <el-table-column label="权重" align="center" prop="weight">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.weight"
              :min="0"
              :max="99"
              :precision="0"
              :step="1"
              controls-position="right"
              @change="handleWeightChange(scope.row)"
              style="width: 80px"
            />
          </template>
        </el-table-column>
        <el-table-column label="所属地区" align="center" prop="areaName" :show-overflow-tooltip="true" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="100">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:guide:edit']">修改</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:guide:remove']">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pagination-container">
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
        :selection="ids.length"
      />
    </div>

    <!-- 添加或修改办事指南对话框 -->
    <div class="guide-dialog">
      <el-dialog :title="title" v-model="open" draggable :close-on-click-modal="false" width="780px" append-to-body>
        <el-form ref="guideRef" :model="form" :rules="rules" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="一级网格" prop="primaryGrid">
                <el-input v-model="form.primaryGrid" placeholder="请输入一级网格" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="二级网格" prop="secondaryGrid">
                <el-input v-model="form.secondaryGrid" placeholder="请输入二级网格" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="网格属性" prop="gridAttributes">
                <el-select v-model="form.gridAttributes" placeholder="请选择网格属性">
                  <el-option v-for="item in gridAttr" :key="item" :label="item" :value="item" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="持证户数" prop="licensedHouseholds">
                <el-input-number
                  v-model="form.licensedHouseholds"
                  :min="0"
                  controls-position="right"
                  placeholder="请输入持证户数"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="户数" prop="numberHouseholds">
                <el-input-number
                  v-model="form.numberHouseholds"
                  :min="0"
                  controls-position="right"
                  placeholder="请输入户数"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="预设户数" prop="preNumber">
                <el-input-number
                  v-model="form.preNumber"
                  :min="0"
                  controls-position="right"
                  placeholder="请输入预设户数"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="差值" prop="difference">
                <el-input-number v-model="form.difference" controls-position="right" placeholder="请输入差值" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="存量提示" prop="stockPrompt">
                <el-select v-model="form.stockPrompt" placeholder="请选择存量提示">
                  <el-option v-for="item in stockPrompt" :key="item" :label="item" :value="item" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="权重" prop="weight">
                <el-input-number
                  v-model="form.weight"
                  :min="0"
                  :max="99"
                  :precision="0"
                  :step="1"
                  controls-position="right"
                  placeholder="请输入权重值(0-99)"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属地区" prop="areaId">
                <tree-select
                  v-model="form.areaId"
                  :options="data.areaOptions"
                  :obj-map="{
                    value: 'areaId',
                    label: 'areaName',
                    children: 'children'
                  }"
                  placeholder="请选择所属地区"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <!-- <el-col :span="12">
              <el-form-item label="状态">
                <el-radio-group v-model="form.status">
                  <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col> -->
            <!-- <el-col :span="24">
              <el-form-item label="内容" prop="content">
                <editor v-model="form.content" :min-height="192" :height="400" />
              </el-form-item>
            </el-col> -->
          </el-row>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
      </el-dialog>
    </div>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="handleImportTemplate">
              下载模板
            </el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm" :loading="upload.isUploading">
            <span v-if="!upload.isUploading">确 定</span>
            <span v-else>导 入 中...</span>
          </el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Guide">
import { listGuide, getGuide, delGuide, addGuide, updateGuide, importTemplate, importData } from '@/api/system/guide'
import { listArea } from '@/api/system/area'
import { getToken } from '@/utils/auth'
import { gridAttr, primaryGrid, stockPrompt } from '@/utils/constants'

const { proxy } = getCurrentInstance()
const { sys_normal_disable } = proxy.useDict('sys_normal_disable')

const guideList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')

const data = reactive({
  form: {},
  areaOptions: [],
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    primaryGrid: undefined,
    secondaryGrid: undefined,
    gridAttributes: undefined,
    licensedHouseholds: undefined,
    numberHouseholds: undefined,
    preNumber: undefined,
    difference: undefined,
    stockPrompt: undefined,
    createBy: undefined,
    status: undefined,
    areaId: undefined
  },
  rules: {
    title: [{ required: true, message: '指南标题不能为空', trigger: 'blur' }],
    weight: [{ required: true, message: '权重不能为空', trigger: 'blur' }],
    content: [{ required: true, message: '指南内容不能为空', trigger: 'blur' }],
    primaryGrid: [{ required: true, message: '一级网格不能为空', trigger: 'blur' }],
    secondaryGrid: [{ required: true, message: '二级网格不能为空', trigger: 'blur' }],
    gridAttributes: [{ required: true, message: '网格属性不能为空', trigger: 'blur' }],
    licensedHouseholds: [{ required: true, message: '持证户数不能为空', trigger: 'blur' }],
    numberHouseholds: [{ required: true, message: '户数不能为空', trigger: 'blur' }],
    preNumber: [{ required: true, message: '预设户数不能为空', trigger: 'blur' }],
    difference: [{ required: true, message: '差值不能为空', trigger: 'blur' }],
    stockPrompt: [{ required: true, message: '存量提示不能为空', trigger: 'blur' }]
  }
})

/*** 导入参数 */
const upload = reactive({
  // 是否显示弹出层（导入）
  open: false,
  // 弹出层标题（导入）
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 设置上传的请求头部
  headers: { Authorization: 'Bearer ' + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/system/guide/importData?updateSupport=true'
})

const { queryParams, form, rules } = toRefs(data)

/** 查询办事指南列表 */
function getList() {
  loading.value = true
  listGuide(queryParams.value).then((response) => {
    if (response.code === 200) {
      guideList.value = response.rows.map((item) => {
        item.createTime = item.updateTime ? item.updateTime : item.createTime
        return item
      })
      total.value = response.total
      loading.value = false
    } else {
      ElMessage.error(response.msg)
    }
  })
}
/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}
/** 表单重置 */
function reset() {
  form.value = {
    guideId: undefined,
    title: undefined,
    content: undefined,
    weight: 99,
    status: '0',
    areaId: undefined,
    primaryGrid: undefined,
    secondaryGrid: undefined,
    gridAttributes: undefined,
    licensedHouseholds: undefined,
    numberHouseholds: undefined,
    preNumber: undefined,
    difference: undefined,
    stockPrompt: undefined
  }
  proxy.resetForm('guideRef')
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef')
  handleQuery()
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.guideId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}
/** 新增按钮操作 */
function handleAdd() {
  reset()
  if (data.areaOptions.length > 0) {
    form.value.areaId = data.areaOptions[0].areaId
  }
  open.value = true
  title.value = '添加网格'
}
/**修改按钮操作 */
function handleUpdate(row) {
  reset()
  const guideId = row.guideId || ids.value
  getGuide(guideId).then((response) => {
    form.value = response.data
    open.value = true
    title.value = '修改网格'
  })
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs['guideRef'].validate((valid) => {
    if (valid) {
      if (form.value.guideId != undefined) {
        updateGuide(form.value).then((response) => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          getList()
        })
      } else {
        addGuide(form.value).then((response) => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}
/** 删除按钮操作 */
function handleDelete(row) {
  const guideIds = row.guideId || ids.value
  proxy.$modal
    .confirm('是否确认删除网格编号为"' + guideIds + '"的数据项？')
    .then(function () {
      return delGuide(guideIds)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

/** 状态修改 */
function handleStatusChange(row) {
  let text = row.status === '0' ? '启用' : '停用'
  proxy.$modal
    .confirm('确认要"' + text + '""' + row.title + '"网格吗？')
    .then(function () {
      return updateGuide({ guideId: row.guideId, status: row.status })
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess(text + '成功')
    })
    .catch(function () {
      row.status = row.status === '0' ? '1' : '0'
    })
}

/** 权重修改 */
function handleWeightChange(row) {
  updateGuide({ guideId: row.guideId, weight: row.weight }).then(() => {
    proxy.$modal.msgSuccess('修改成功')
    getList()
  })
}

/** 导入按钮操作 */
function handleImport() {
  upload.title = '网格导入'
  upload.open = true
}

/** 下载模板操作 */
function handleImportTemplate() {
  proxy.download('system/guide/importTemplate', {}, `guide_template_${new Date().getTime()}.xlsx`)
}

/**文件上传中处理 */
function handleFileUploadProgress(event, file, fileList) {
  upload.isUploading = true
}

/** 文件上传成功处理 */
function handleFileSuccess(response, file, fileList) {
  upload.open = false
  upload.isUploading = false
  proxy.$refs['uploadRef'].handleRemove(file)
  proxy.$alert(
    "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>',
    '导入结果',
    { dangerouslyUseHTMLString: true }
  )
  getList()
}

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs['uploadRef'].submit()
}

onMounted(() => {
  getList()
  // 初始化地区数据，用于查询表单
  listArea().then((response) => {
    data.areaOptions = proxy.handleTree(response.data, 'areaId')
    // if (data.areaOptions.length > 0) {
    //   queryParams.value.areaId = data.areaOptions[0].areaId
    // }
  })
})
</script>

<style lang="scss" scoped>
@import '@/assets/styles/guide-form.scss';

.guide-container {
  .guide-search {
    margin-bottom: 15px;
  }

  .guide-table {
    overflow: hidden;
  }
}
</style>
